package com.atguigu.boot.controller;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

public class Demo {

    public static void main(String[] args) {
        String appId = "123434";
        String appKey = "asdfds2342342";

        Map<String, String> params = new HashMap<>();
        params.put("phone", "13888888");
        params.put("app_id", appId);
        params.put("timestamp",String.valueOf(System.currentTimeMillis()/1000));

        StringBuilder sb = new StringBuilder();
        // 将参数以参数名的字典升序排序
        Map<String, String> sortParams = new TreeMap<>(params);

        // 遍历排序的字典,并拼接"key=value"格式
        for (Map.Entry<String, String> entry : sortParams.entrySet()) {
            String key = entry.getKey();
            String value =  entry.getValue().trim();
            sb.append("&").append(key).append("=").append(value);
        }
        String stringA = sb.toString().replaceFirst("&","");
        // 在后面拼接key获得加密前字符串
        String stringSignTemp = stringA + "&key=" + appKey;
        // md5加密
        String md5Str = md5(stringSignTemp);
        //把md5后的数据转大写获得签名
        String sign = md5Str.toUpperCase();
        //追加到post参数中
        params.put("sign", sign);
        System.out.println(params);
    }

    private static String md5(String dataStr) {
        try {
            MessageDigest m = MessageDigest.getInstance("MD5");
            m.update(dataStr.getBytes(StandardCharsets.UTF_8));
            byte s[] = m.digest();
            StringBuilder result = new StringBuilder();
            for (byte b : s) {
                result.append(Integer.toHexString((0x000000FF & b) | 0xFFFFFF00).substring(6));
            }
            return result.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "";
    }
}